package com.futureCloudMOM.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.futureCloudMOM.common.exception.base.BaseException;
import com.futureCloudMOM.core.base.service.impl.BaseServiceImpl;
import com.futureCloudMOM.core.domain.*;
import com.futureCloudMOM.core.mapper.BasicBillTypeMapper;
import com.futureCloudMOM.core.mapper.WmsInvoiceMainMapper;
import com.futureCloudMOM.core.mapper.WmsInvoiceSubMapper;
import com.futureCloudMOM.core.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 【WMS_InvoiceMain】的数据库操作Service实现
 *
 * @author Administrator
 * @since 2023-06-07 09:14:44
 */
@AllArgsConstructor
@Log4j2
@Service
public class WmsInvoiceMainServiceImpl extends BaseServiceImpl<WmsInvoiceMainMapper, WmsInvoiceMain> implements WmsInvoiceMainService {

    // 业务订单主表
    private final WmsInvoiceMainMapper wmsInvoiceMainMapper;
    // 业务订单子表
    private final WmsInvoiceSubMapper wmsInvoiceSubMapper;
    // 源单子表
    private final WmsErpSourceSubService wmsErpSourceSubService;
    // 订单类型
    private final BasicBillTypeMapper basicBillTypeMapper;
    // 条码表
    private final WmsBarCodeInfoService barCodeInfoService;
    //条码库位
    private final WmsBarCodeQuanService barCodeQuanService;
    // 条码事务
    private final WmsBarCodeTransferService barCodeTransferService;

    @Override
    @Transactional
    public WmsInvoiceMain add(WmsInvoiceMain wmsInvoiceMain) {
        if (wmsInvoiceMain.getList().size() > 0) {
            wmsInvoiceMain.getList().forEach(item -> {
                // 获取源单未关联数量
                WmsErpSourceSub wmsErpSourceSub = wmsErpSourceSubService.getById(item.getSrcBillSubId());
                if (item.getQty().compareTo(wmsErpSourceSub.getNotRelationQty()) > 0)
                    throw new RuntimeException("行号:" + item.getRowNum() + "的订单数量不能大于源单数量");
                item.setMainId(wmsInvoiceMain.getId());
                wmsInvoiceSubMapper.insert(item);
                // 扣除源单数量
                wmsErpSourceSubService.deductQty(item.getSrcBillId(), item.getSrcBillSubId(), item.getQty());
            });
        }
        wmsInvoiceMainMapper.insert(wmsInvoiceMain);
        return wmsInvoiceMain;
    }

    @Override
    @Transactional
    public void edit(WmsInvoiceMain wmsInvoiceMain) {
        if (wmsInvoiceMain.getList().size() > 0) {
            wmsInvoiceMain.getList().forEach(item -> {
                if (ObjectUtils.isNotEmpty(item.getId())) {
                    // 判断子表的数量是否修改
                    WmsInvoiceSub wmsInvoiceSub = wmsInvoiceSubMapper.selectById(item.getId());
                    int flag = wmsInvoiceSub.getQty().compareTo(item.getQty());
                    switch (flag) {
                        // 修改后的数量大于原本的数量 源单数量需要扣减
                        case -1:
                            wmsErpSourceSubService.deductQty(item.getSrcBillId(), item.getSrcBillSubId(), item.getQty().subtract(wmsInvoiceSub.getQty()));
                            break;
                        // 修改后的数量小于原本的数量 源单数量需要回写
                        case 1:
                            wmsErpSourceSubService.backQty(item.getSrcBillId(), item.getSrcBillSubId(), wmsInvoiceSub.getQty().subtract(item.getQty()));
                            break;
                    }
                    // 更新子表数据
                    wmsInvoiceSubMapper.updateById(item);
                } else {
                    // 新增的需要从源单扣减数量


                    // 新增
                    item.setMainId(wmsInvoiceMain.getId());
                    wmsInvoiceSubMapper.insert(item);
                }
            });
        }
        // 子表需要删除的数据
        if (ObjectUtils.isNotEmpty(wmsInvoiceMain.getIds())) {
            // 删除的数量需要返还给源单


            // 删除
            wmsInvoiceMain.getIds().forEach(wmsInvoiceSubMapper::deleteById);
        }
        // 更新主表
        wmsInvoiceMainMapper.updateById(wmsInvoiceMain);
    }

    @Override
    @Transactional
    public void submit(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        if (wmsInvoiceMain.getStatus() != 0) {
            throw new BaseException("新建状态的业务订单才可以提交");
        }
        // 根据主表ID查询业务订单详情
        List<WmsInvoiceSub> wmsInvoiceSubList = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId, id)
                .eq(WmsInvoiceSub::getDeleted, 0));
        wmsInvoiceSubList.forEach(item -> {
            // 根据源单子表ID查询源单子表信息
            WmsErpSourceSub wmsErpSourceSub = wmsErpSourceSubService.getById(item.getSrcBillSubId());
            // 判断业务订单子表的数量是否超出源单的未关联数量
            if (item.getQty().compareTo(wmsErpSourceSub.getNotRelationQty()) > 0) {
                throw new BaseException("源单单号：【" + item.getSrcBillNo() + "】的数量超出源单的未关联数量，请检查");
            } else {
                // 数量核销成功 源单数量扣除
                wmsErpSourceSubService.deductQty(id, item.getId(), item.getQty());
            }
        });
        // 状态改为待审核
        wmsInvoiceMain.setStatus(1L);
        updateById(wmsInvoiceMain);
    }

    @Override
    @Transactional
    public void cancellation(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        // 草稿状态允许作废
        if (wmsInvoiceMain.getStatus() == 0) {
            // 主表状态作废
            wmsInvoiceMain.setStatus(-1L);
            wmsInvoiceMainMapper.updateById(wmsInvoiceMain);
            // 查询该订单子表信息
            List<WmsInvoiceSub> wmsInvoiceSubs = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                    .eq(WmsInvoiceSub::getMainId, id)
                    .eq(WmsInvoiceSub::getDeleted, 0));
            wmsInvoiceSubs.forEach(item -> {
                // 子表状态关闭
                item.setStatus(1L);
                wmsInvoiceSubMapper.updateById(item);
            });
        } else {
            throw new RuntimeException("新建状态的订单才允许作废");
        }
    }

    @Override
    @Transactional
    public void forcedClose(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        if (wmsInvoiceMain.getStatus() == 3) {
            throw new BaseException("该订单已关闭");
        }
        // 查询该订单子表信息
        List<WmsInvoiceSub> wmsInvoiceSubs = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId, wmsInvoiceMain.getId())
                .eq(WmsInvoiceSub::getDeleted, 0));
        wmsInvoiceSubs.forEach(item -> {
            // 计算需要回写的数量
            BigDecimal backQty = item.getQty().subtract(item.getRelationQty());
            item.setQty(item.getRelationQty());
            item.setNotRelationQty(new BigDecimal(0));
            item.setStatus(1L);
            wmsInvoiceSubMapper.updateById(item);
            // 回写源单数量
            wmsErpSourceSubService.backQty(item.getSrcBillId(), item.getSrcBillSubId(), backQty);
        });
        // 业务订单主表的状态修改至强制关闭
        wmsInvoiceMain.setStatus(5L);
        wmsInvoiceMainMapper.updateById(wmsInvoiceMain);

        // 入库类订单还需将未执行的条码删除
        BasicBillType basicBillType = basicBillTypeMapper.selectById(wmsInvoiceMain.getBillType());
        // 判断该订单是否是入库类订单
        if (basicBillType.getInOutFlag() == 1) {
            // 删除未执行的条码
            wmsInvoiceSubs.forEach(item -> {
                // 查询未执行的条码并删除
                barCodeInfoService.delByState(item.getSrcBillId(), item.getSrcBillSubId());
            });
        }
    }

    @Override
    public void submitAndStockMarker(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        if (wmsInvoiceMain.getStatus() != 0) {
            throw new BaseException("新建状态的业务订单才可以提交");
        }
        // 根据主表ID查询业务订单详情
        List<WmsInvoiceSub> wmsInvoiceSubList = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId, id)
                .eq(WmsInvoiceSub::getDeleted, 0));
        // 备货
        barCodeInfoService.stockMarkerByInvoiceSub(wmsInvoiceSubList, wmsInvoiceMain.getBillType());
        // 获取备货后的子表数据 并且只要备货成功的
        List<WmsInvoiceSub> wmsInvoiceSubs = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId, id)
                .eq(WmsInvoiceSub::getDeleted, 0)
                .eq(WmsInvoiceSub::getStockMarker, 0));
        if(ObjectUtils.isEmpty(wmsInvoiceSubs)){
            throw new BaseException("所有物料都备货失败，请联系相关人员解决");
        }
        // 备货成功的子表数据跟源单进行核销
        wmsInvoiceSubs.forEach(item -> {
            // 根据源单子表ID查询源单子表信息
            WmsErpSourceSub wmsErpSourceSub = wmsErpSourceSubService.getById(item.getSrcBillSubId());
            // 判断业务订单子表的数量是否超出源单的未关联数量
            if (item.getQty().compareTo(wmsErpSourceSub.getNotRelationQty()) > 0) {
                throw new BaseException("源单单号：【" + item.getSrcBillNo() + "】的数量超出源单的未关联数量，请检查");
            } else {
                // 数量核销成功 源单数量扣除
                wmsErpSourceSubService.deductQty(id, item.getId(), item.getQty());
            }
        });
        // 状态改为待审核
        wmsInvoiceMain.setStatus(1L);
        updateById(wmsInvoiceMain);
    }

    @Override
    @Transactional
    public void orderReview(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        if (wmsInvoiceMain.getStatus() != 1) {
            throw new BaseException("待审核的订单才可以进行审核");
        }
        //订单状态修改
        wmsInvoiceMain.setStatus(2L);
        wmsInvoiceMainMapper.updateById(wmsInvoiceMain);
        // 入库类订单生成条码
        BasicBillType basicBillType = basicBillTypeMapper.selectById(wmsInvoiceMain.getBillType());
        if (basicBillType.getInOutFlag() == 1) {
            //生成条码
            barCodeInfoService.CreateBarCode(id);
        }
    }

    @Override
    @Transactional
    public void orderDeApproval(Long id) {
        // 查询最新的订单信息
        WmsInvoiceMain wmsInvoiceMain = getById(id);
        if (wmsInvoiceMain.getStatus() != 2) {
            throw new BaseException("已审核的订单才可以进行反审核");
        }
        //订单状态修改
        wmsInvoiceMain.setStatus(0L);
        wmsInvoiceMainMapper.updateById(wmsInvoiceMain);
        // 入库类订单生成的条码删除
        BasicBillType basicBillType = basicBillTypeMapper.selectById(wmsInvoiceMain.getBillType());
        if (basicBillType.getInOutFlag() == 1) {
            //条码删除
            barCodeInfoService.DelBarCode(id);
        }
        // 源单数量回写
        // 查询该订单子表信息
        List<WmsInvoiceSub> wmsInvoiceSubs = wmsInvoiceSubMapper.selectList(new LambdaQueryWrapper<WmsInvoiceSub>()
                .eq(WmsInvoiceSub::getMainId, id)
                .eq(WmsInvoiceSub::getDeleted, 0));
        wmsInvoiceSubs.forEach(item -> {
            item.setNotRelationQty(item.getQty());
            item.setRelationQty(BigDecimal.ZERO);
            item.setStatus(1L);
            wmsInvoiceSubMapper.updateById(item);
            // 回写源单数量
            wmsErpSourceSubService.backQty(item.getSrcBillId(), item.getSrcBillSubId(), item.getQty());
        });
    }


}
